import React, { Component } from 'react';
import { Table, Input, Button, Popconfirm, Form,Select, Modal,  Divider, Icon} from 'antd';
import Content from "../../components/Content/Content";
import moment from "moment";

const EditableContext = React.createContext();
const { Option } = Select;
const InputGroup = Input.Group;
const { TextArea } = Input;

const dateFormater = 'YYYY-MM-DD HH:mm:ss';

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
function handleChange(value) {
  console.log(`selected ${value}`);
}
class EditableCell extends React.Component {
  state = {
    editing: false,
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
    visible: false,
    visible1: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`,
            },
          ],
          initialValue: record[dataIndex],
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        editable: false,
        fixed: 'left',
        width:120,
      },
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '菌株保藏编号',
        dataIndex: 'jzbc_id',
        editable: true,
      },
      {
        title: '菌种类别',
        dataIndex: 'add_jyjz',
        render: (text, record) => (
          <Select defaultValue={text}
          // mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({add_jyjz : value}) }
          tokenSeparators={','}
          showArrow={true}
         >
            <Option value="fxj">放线菌</Option>
            <Option value="xj">细菌</Option>
            <Option value="xxzj">真菌（小型真菌）</Option>
            <Option value="jmzj">真菌（酵母）</Option>
            <Option value="dxzj">真菌（大型真菌）</Option>
            <Option value="qt">其他类型</Option>
          </Select>
              )
      },
      {
        title: '新增分离菌株编号',
        dataIndex: 'add_separate_num',
      },
      {
        title: '近缘菌株',
        dataIndex: 'r_jyjz',
      },
      {
        title: '菌株序列',
        dataIndex: 'info_jzxl',
      },
      {
        title: '采集样品编号',
        dataIndex: 'Acq_id',
      },
      {
        title: '分离培养基编号',
        dataIndex: 'a_flpyjbh',
      },
      {
        title: '传代培养基编号',
        dataIndex: 'a_cdpyjid',
      },
      {
        title: '菌株图片',
        dataIndex: 'sxjj_pic',
        render: (text, record) => (
          <Form>
            <Button onClick={value => document.getElementById("sxjj_pic" + record.id).click()}>
              <Icon type="upload" /> 上传
            </Button>
            <Input readOnly id={"sxjj_pic" + record.id} type="file" onChange={env => this.selectFile(env, 'sxjj_pic', record.id)} style={{display: 'none'}} />
          </Form>
        )
      },
      {
        title: '培养温度',
        dataIndex: 'info_wd',
        editable: true,
      },
      {
        title: '培养周期',
        dataIndex: 'info_date',
        editable: true,
      },
      {
        title: '分离人',
        dataIndex: 'info_person',
      },
      {
        title: '分离时间',
        dataIndex: 'info_time',
      },
      {
        title: '需氧类型',
        dataIndex: 'a_xylx',
        render: (text, record) => (
          <Select defaultValue={text}
            // mode="tags"
            style={{ width: "100%" }}
            onChange={value => this.setState({a_xylx : value}) }
            tokenSeparators={','}
            showArrow={true}
          >
            <Option value="XY">需氧</Option>
            <Option value="YY">厌氧</Option>
            <Option value="BH">饱和</Option>
          </Select>
          )
      },
      {
        title: '菌落描述',
        dataIndex: 'a_jlms',
        editable: true,
      },
      {
        title: '正面颜色',
        dataIndex: 'info_zmys',
        editable: true,
      },
      {
        title: '反面颜色',
        dataIndex: 'info_fmys',
        editable: true,
      },
      {
        title: '孢子有无',
        dataIndex: 'info_bzyw',
        editable: true,
      },
      {
        title: '是否产色素',
        dataIndex: 'info_css',
        editable: true,
      },
      {
        title: '菌株价值标记',
        dataIndex: 'jzjz_tag',
        render: (text, record) => (
          <Select defaultValue={text}
          //mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({jzjz_tag : value}) }
          tokenSeparators={','}
          showArrow={true}
        >
          <Option value="pt">普通</Option>
          <Option value="qzdwz">潜在多物种</Option>
          <Option value="dyx">多样性</Option>
        </Select>
              )
      },
      {
        title: '入库人员姓名',
        dataIndex: 'worker',
        editable: true,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width:260,
        render: (text, record) => (
          <span>
            <Button disabled={record.chuli_tag == 'yjs'} onClick={()=>this.jieShou(record)} type="dashed">
              接收
            </Button>
            <Divider type="vertical" />
            <Button disabled={record.chuli_tag == 'th'} onClick={()=>this.showModal_tuihui(record)} type="dashed" >
              退回
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
              <Button type="dashed" >删除</Button>
            </Popconfirm>
          </span>
        )
      },
    ];
    this.columns1 = [
      {
        title: 'ID',
        dataIndex: 'id',
        editable: false,
        fixed: 'left',
        width:120,
      },
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '菌株保藏编号',
        dataIndex: 'jzbc_id',
        editable: true,
      },
      {
        title: '菌种类别',
        dataIndex: 'add_jyjz',
      },
      {
        title: '新增分离菌株编号',
        dataIndex: 'add_separate_num',
      },
      {
        title: '近缘菌株',
        dataIndex: 'r_jyjz',
      },
      {
        title: '菌株序列',
        dataIndex: 'info_jzxl',
      },
      {
        title: '采集样品编号',
        dataIndex: 'Acq_id',
      },
      {
        title: '分离培养基编号',
        dataIndex: 'a_flpyjbh',
      },
      {
        title: '传代培养基编号',
        dataIndex: 'a_cdpyjid',
      },
      {
        title: '菌株图片',
        dataIndex: 'sxjj_pic'
      },
      {
        title: '培养温度',
        dataIndex: 'info_wd',
        editable: true,
      },
      {
        title: '培养周期',
        dataIndex: 'info_date',
        editable: true,
      },
      {
        title: '分离人',
        dataIndex: 'info_person',
      },
      {
        title: '分离时间',
        dataIndex: 'info_time',
      },
      {
        title: '需氧类型',
        dataIndex: 'a_xylx',
      },
      {
        title: '菌落描述',
        dataIndex: 'a_jlms',
        editable: true,
      },
      {
        title: '正面颜色',
        dataIndex: 'info_zmys',
        editable: true,
      },
      {
        title: '反面颜色',
        dataIndex: 'info_fmys',
        editable: true,
      },
      {
        title: '孢子有无',
        dataIndex: 'info_bzyw',
        editable: true,
      },
      {
        title: '是否产色素',
        dataIndex: 'info_css',
        editable: true,
      },
      {
        title: '菌株价值标记',
        dataIndex: 'jzjz_tag',
      },
      {
        title: '入库人员姓名',
        dataIndex: 'worker',
        editable: true,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        editable: true,
      },
    ];
    this.state = {
      dataSource: [],
      dataSource_yikuli: [],
      count: 0,
      count_yichuli: 0,
      newData: {},
      loading: false,
      keyword: '',

      add_jyjz : '',
      jzbc_type : '',
      a_xylx:'',
      jzjz_tag: '',
      sxjj_pic:'',

      visible_yichuli: false,
      visible_tuihui: false,
      record_tuihui: null, // 退回的ID
      msg_tuihui: null,

    };
  }

  handleDelete = id => {
    const dataSource = [...this.state.dataSource];

    // 如果是新数据尚未保存，那么可以直接删除
    if( this.state.newData.id != null ) {
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      return;
    }

    const url = global.api.screeningLibraryInfo + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      this.setState({ dataSource: dataSource.filter(item => item.id !== id), newData: {} });
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    }) 
  };

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  selectFile = (env, prefix, idx) => {
    let files = env.target.files;
    let filename = files[0].name;
    // document.getElementById(prefix + idx).value = filename;
    this.setState({sxjj_pic: files[0]});
  }

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 200;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }
    
    const newData = {
      id: initVal,
      sxjj_id: initVal,
      jzbc_id : initVal,
      add_jyjz  : initVal,
      add_separate_num  : initVal,

      r_jyjz  : initVal,
      info_jzxl  : initVal,
      Acq_id  : initVal,

      a_flpyjbh: initVal,
      a_cdpyjid : initVal,
      sxjj_pic : initVal,
      info_wd: initVal,

      info_date : moment(new Date(), "DD").format("DD"),
      info_person : initVal,
      info_time : moment(new Date(), dateFormater).format(dateFormater),
      a_xylx : '',

      a_jlms: initVal,
      info_zmys : initVal,
      info_fmys : initVal,
      info_bzyw: initVal,

      info_css: initVal,
      jzjz_tag  : '',
      remark : initVal,
      worker: initVal
    };

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      newData: newData
    });
  };

  showModal_yichuli = () => {
    // 先调用接口获取数据，成功后显示Modal
    const url = global.api.ScreeningLibraryReviewYichuli;
    return global.getdata.get(url, {page_index: 1, page_size: this.state.pageSize})
    .then(res => {
      this.setState({visible_yichuli: true, dataSource_yikuli: res, count_yichuli: res.length})
    })
    .catch(err => {
      Modal.error({
        content: '数据获取失败！'
      })
    })
  };

  showModal_tuihui = (record) => {
    this.setState({
      visible_tuihui: true,
      record_tuihui: record
    });
  };
  handleOk_tuihui = e => {
    this.setState({
      visible_tuihui: false,
    });
  };
  handleCancel_tuihui = e => {
    this.setState({
      visible_tuihui: false,
    });
  };
  handleOk_yichuli = e => {
    this.setState({
      visible_yichuli: false,
    });
  };
  handleCancel_yichuli = e => {
    this.setState({
      visible_yichuli: false,
    });
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.screeningLibraryInfo;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: this.state.keyword})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  handleSave = (row, showAlert) => {
   
    let dataSource = [...this.state.dataSource];
    let record = null;
    if( row.id != null ) {
      record = row;
    } else {
      record = dataSource[dataSource.length - 1];
    }

    record.a_xylx = this.state.a_xylx;
    record.jzbc_type = this.state.jzbc_type;
    record.jzjz_tag = this.state.jzjz_tag;
    record.add_jyjz = this.state.add_jyjz;
    record.sxjj_pic = document.getElementById('sxjj_pic' + record.id).files[0];

    const formData = new FormData();
    Object.keys(record).forEach((key) => {
      formData.append(key, record[key]);
    });

    const url = global.api.screeningLibraryInfo;
    return global.network.post(url, formData)
    .then(res => {  
      this.setState({newData: {}});
      this.loadData(1);
      if( showAlert ) {
        Modal.success({
          content: '保存成功!',
        });
      }
    })
    .catch(err => {
      if( showAlert ) {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
      }
    }) 

  };

  // 入库 或者叫 处理
  doRuku = () => {
     let selectedRowKeys = this.state.selectedRowKeys;
     if(selectedRowKeys) {
       for( let x of selectedRowKeys ) {
         let record = this.state.dataSource[x];
         record.chuli_tag = 'yjs'; // wcl\yjs\yth

         const url = global.api.huijiaoinfo + record.id + '/';
         return global.updatedata.put(url, record)
         .then(res => {  
     
          this.loadData(1);
     
           Modal.success({
             content: '处理成功!',
           });
         })
         .catch(err => {           
           Modal.error({
             content: '处理出错!',
           });
         }) 

       }
     }
  }

  // 退回
  doBack = () => {
    let msg = this.state.msg_tuihui;
    let record = this.state.record_tuihui;

    record.chuli_tag = 'yth';
    record.back_reason = msg;

    let url = global.api.huijiaoinfo + record.id + '/';
    
    global.updatedata.put(url, record)
    .then(res => {  
      
      // 再次调用strainback
      url = global.api.strainBack;
      record.chuli_tag = 'th';

      return global.network.post(url, record)
      .then(res => {  

          this.loadData(1);
                  
          Modal.success({
            content: '退回成功!',
          });
        }) 
        .catch(err => {           
            Modal.error({
              content: '退回出错!',
          });
      });
      
    })
    .catch(err => {           
      Modal.error({
        content: '退回出错!',
      });
    }) 

  }

  // 接收
  jieShou = (record) => {
    record.chuli_tag = 'yjs';

    const url = global.api.huijiaoinfo + record.id + '/';
    return global.updatedata.put(url, record)
    .then(res => {  
      this.loadData(1);
            
      Modal.success({
        content: '接收成功!',
      });
    })
    .catch(err => {           
      Modal.error({
        content: '接收出错!',
      });
    }) 

  }
  

  render() {
    const { dataSource, dataSource_yikuli, loading, selectedRowKeys } = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns1= this.columns1.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <Content>
          <div className="filtrate">
          <p style={{marginLeft:'100px'}}>
          <span className="span">
         <Input placeholder="输入查询内容" style={{ width: 250 }}  onChange={e => this.setState({keyword: e.target.value})} />
          </span>
          <span className="span" >
            <Button loading={this.state.loading} type="primary" style={{ width: 80 }} onClick={this.loadData.bind('click', 1)}>
              查询
            </Button>
          </span>
          </p>
        </div>
        <div style={{marginTop: '50px',marginLeft: 16}}>
        <Button  onClick={this.doRuku} type="primary" >
          处理
        </Button>
        <Button  type="primary" onClick={this.showModal_yichuli} style={{marginLeft: 16}}>
          已处理
        </Button>
         </div>

        <Modal
          title="Basic Modal"
          visible={this.state.visible_yichuli}
          onOk={this.handleOk_yichuli}
          onCancel={this.handleCancel_yichuli}
        >
        
        <Table
          // rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource_yikuli}
          columns={columns1}
          scroll={{ x: 3500}}
        />
        </Modal>
        <Modal
          title="Basic Modal"
          visible={this.state.visible_tuihui}
          onOk={this.handleOk_tuihui}
          onCancel={this.handleCancel_tuihui}
        >
          <TextArea onChange={e => this.setState({msg_tuihui: e.target.value})} placeholder="输入退回原因" style={{marginTop:'50px',marginBottom:'24px'}} />
          <Button onClick={this.doBack} type="primary" style={{ marginLeft: 16 }}>
            确定
          </Button>
        </Modal>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          scroll={{ x: 3500}}
        />
        <div style={{marginLeft: 16}}>
        <Button onClick={this.handleAdd} type="primary" >
          添加
        </Button>
        <Button disabled={this.state.newData.id == null} onClick={(record) => this.handleSave(record, true)}  type="primary" style={{ marginLeft: 16 }}>
          保存
        </Button>
         </div>
      </Content>
    );
  }
}

const ScreeningSaveInfo = Form.create()(EditableTable);
export default ScreeningSaveInfo;